package com.stars.questions.commonQuestion.config.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stars.base.constants.CommonNumberConstants;
import com.stars.base.entity.CommonDTO;
import com.stars.questions.commonQuestion.config.entity.QuestionsCommonConfig;
import com.stars.questions.commonQuestion.config.entity.QuestionsCommonConfigSub;
import com.stars.questions.commonQuestion.config.mapper.QuestionsCommonConfigMapper;
import com.stars.questions.commonQuestion.config.mapper.QuestionsCommonConfigSubMapper;
import com.stars.questions.commonQuestion.config.service.QuestionsCommonConfigService;
import com.stars.util.common.DevelopKit;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 问卷配置服务实现类
 * @author : moon
 * @date :  2024/6/29 16:51
 */
@Service
public class QuestionsCommonConfigServiceImpl implements QuestionsCommonConfigService {

    private final QuestionsCommonConfigMapper questionMapper;

    private final QuestionsCommonConfigSubMapper subMapper;

    private final SqlSessionFactory sqlSessionFactory;

    private static final Logger logger = LoggerFactory.getLogger(QuestionsCommonConfigServiceImpl.class);



    public QuestionsCommonConfigServiceImpl(QuestionsCommonConfigMapper questionMapper, QuestionsCommonConfigSubMapper subMapper, SqlSessionFactory sqlSessionFactory) {
        this.questionMapper = questionMapper;
        this.subMapper = subMapper;
        this.sqlSessionFactory = sqlSessionFactory;
    }


    @Override
    public JSONObject configList(CommonDTO dto) {

        JSONObject result = new JSONObject();

        Page<QuestionsCommonConfig> page = Page.of(dto.getCurrent(), dto.getPageSize());
        LambdaQueryWrapper<QuestionsCommonConfig> queryWrapper = new LambdaQueryWrapper<>();

        if(StringUtils.hasLength(dto.getSearch())){
            queryWrapper.like(QuestionsCommonConfig::getBt, dto.getSearch());
        }

        Page<QuestionsCommonConfig> questionPage = questionMapper.selectPage(page, queryWrapper);

        result.put("list", questionPage.getRecords() );
        result.put("total", questionPage.getTotal());

        return result;
    }

    @Override
    public QuestionsCommonConfig getPublishQuestion(String id) {
        LambdaQueryWrapper<QuestionsCommonConfig> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(QuestionsCommonConfig::getId, id);
        queryWrapper.eq(QuestionsCommonConfig::getPublish, CommonNumberConstants.ONE_NUM);
        queryWrapper.lt(QuestionsCommonConfig::getStartDate, new Date());
        queryWrapper.gt(QuestionsCommonConfig::getEndDate, new Date());

        return questionMapper.selectOne(queryWrapper);
    }

    @Override
    public List<QuestionsCommonConfigSub> loadQuestionSub(String id) {

        LambdaQueryWrapper<QuestionsCommonConfigSub> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(QuestionsCommonConfigSub::getFid, id);
        queryWrapper.orderByAsc(QuestionsCommonConfigSub::getShowOrder);

        return subMapper.selectList(queryWrapper);
    }

    @Override
    public Set<Integer> generateRandomNum(QuestionsCommonConfig question, int questionCount) {
        if(question.getNum()==null || question.getNum()<1 || question.getNum() >= questionCount){
            return null;
        }
        Random random = new Random();

        Set<Integer> set = new HashSet<>();

        while(set.size()<question.getNum()){
            int index = random.nextInt(questionCount);
            set.add(index);
        }

        return set;
    }

    /**
     * 根据问卷ID获取问卷实体
     * @author : moon
     * @date :  2024/6/29 17:30
     * @param: id 主键id
     * @return: java.lang.Object
     */
    @Override
    public QuestionsCommonConfig loadQuestionData(String id) {
        LambdaQueryWrapper<QuestionsCommonConfigSub> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(QuestionsCommonConfigSub::getFid,id);
        queryWrapper.orderByAsc(QuestionsCommonConfigSub::getShowOrder);

        QuestionsCommonConfig question = questionMapper.selectById(id);

        if(question == null){
            question = new QuestionsCommonConfig();
        } else {
            List<QuestionsCommonConfigSub> subs = subMapper.selectList(queryWrapper);
            question.setQuestions(subs);
        }

        return question;
    }

    /**
     * 保存问卷，批量提交事务
     * @author : moon
     * @date :  2024/6/30 12:04
     * @param: question 问卷实体
     * @return: boolean
     */
    @Override
    public boolean formSave(QuestionsCommonConfig question) {

        boolean result = true;
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
        QuestionsCommonConfigMapper configMapper = sqlSession.getMapper(QuestionsCommonConfigMapper.class);
        QuestionsCommonConfigSubMapper configSubMapper = sqlSession.getMapper(QuestionsCommonConfigSubMapper.class);

        if(!StringUtils.hasLength(question.getId())){
            //新增
            String configId = DevelopKit.generateUUID();

            question.setId(configId);
            DevelopKit.setBaseInfo(question);

            configMapper.insert(question);

            for (QuestionsCommonConfigSub sub : question.getQuestions()) {

                sub.setId(DevelopKit.generateUUID());
                sub.setFid(configId);
                sub.setRowStatus(1);

                configSubMapper.insert(sub);
            }

        }else{
            //更新
            configMapper.updateById(question);

            for (QuestionsCommonConfigSub sub : question.getQuestions()) {

                if(!StringUtils.hasLength(sub.getId())){
                    //子表执行新增操作
                    sub.setId(DevelopKit.generateUUID());
                    sub.setFid(question.getId());
                    sub.setRowStatus(1);

                    configSubMapper.insert(sub);
                }else{
                    //子表执行更新操作
                    configSubMapper.updateById(sub);
                }
            }
        }

        try {
            sqlSession.commit();
        } catch (Exception e) {
            result = false;
            logger.error(e.getMessage(),e);
            sqlSession.rollback();
        } finally {
            try {
                sqlSession.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * 删除问卷
     * @author : moon
     * @date :  2024/6/30 12:04
     * @param: id 问卷id
     * @return: boolean
     */
    @Override
    public boolean delRecord(String id) {
        return questionMapper.deleteById(id) > 0;
    }

    /**
     * 问卷取消发布
     * @author : moon
     * @date :  2024/6/30 12:03
     * @param: id 问卷id
     * @return: boolean
     */
    @Override
    public boolean unPublish(String id) {

        QuestionsCommonConfig question = new QuestionsCommonConfig();
        question.setId(id);
        question.setPublish(-1);

        return questionMapper.updateById(question) > 0;
    }

    /**
     * 问卷发布，同时取消其他问卷
     * @author : moon
     * @date :  2024/6/30 12:02
     * @param: id 问卷id
     * @return: com.alibaba.fastjson2.JSONObject
     */
    @Override
    @Transactional
    public JSONObject publish(String id) {

        JSONObject result = new JSONObject();
        result.put("result",false);

        /*LambdaQueryWrapper<QuestionsCommonConfig> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(QuestionsCommonConfig::getPublish, 1);
        queryWrapper.lt(QuestionsCommonConfig::getStartDate, new Date());
        queryWrapper.gt(QuestionsCommonConfig::getEndDate, new Date());

        QuestionsCommonConfig question = questionMapper.selectOne(queryWrapper);

        if(question!=null&&id.equals(question.getId())){
            //当前问卷调查已经发布
            result.put("msg","当前问卷已发布！");
            return result;
        }*/

        QuestionsCommonConfig temp = new QuestionsCommonConfig();
        /*temp.setPublish(-1);

        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(QuestionsCommonConfig::getId,id);

        //取消发布非本数据的问卷
        questionMapper.update(temp,queryWrapper);*/

        temp.setPublish(1);
        temp.setId(id);

        if(questionMapper.updateById(temp) < 1){
            result.put("msg","发布异常！");
            return result;
        }

        result.put("result",true);
        return result;
    }

    /**
     * 删除子表数据
     * @author : moon
     * @date :  2024/6/30 12:02
     * @param: subId 子表id
     * @return: boolean
     */
    @Override
    public boolean deleteSub(String subId) {
        return subMapper.deleteById(subId) > 0;
    }

}
